package top.defaults.colorpicker;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.RadialShader;
import ohos.agp.render.Shader;
import ohos.agp.render.SweepShader;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.app.Context;

/**
 * ColorWheelPalette
 *
 * @author: jjy
 * @since 2021-04-16
 */
public class ColorWheelPalette extends Component implements Component.DrawTask {

    private float radius;
    private float centerX;
    private float centerY;

    private Paint huePaint;
    private Paint saturationPaint;

    /**
     * 构造函数
     *
     * @param context context对象
     */
    public ColorWheelPalette(Context context) {
        this(context, null);
    }

    /**
     * 构造函数
     *
     * @param context context对象
     * @param attrs 属性值
     */
    public ColorWheelPalette(Context context, AttrSet attrs) {
        this(context, attrs, 0);
    }

    /**
     * 构造函数
     *
     * @param context context对象
     * @param attrs 属性值
     * @param defStyleAttr 样式名称
     */
    public ColorWheelPalette(Context context, AttrSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        huePaint = new Paint();
        huePaint.setAntiAlias(true);
        saturationPaint = new Paint();
        saturationPaint.setAntiAlias(true);
        invalidate();
    }

    /**
     * viewsize改变监听
     *
     * @param width width
     * @param height height
     */
    protected void onSizeChanged(int width, int height) {
        int netWidth = width - getPaddingLeft() - getPaddingRight();
        int netHeight = height - getPaddingTop() - getPaddingBottom();
        radius = Math.min(netWidth, netHeight) * 0.5f;
        if (radius < 0) {
            return;
        }
        centerX = width * 0.5f;
        centerY = height * 0.5f;
        Shader hueShader = new SweepShader(centerX, centerY,
            new Color[]{Color.RED, Color.MAGENTA, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, Color.RED},
            null);
        huePaint.setShader(hueShader, Paint.ShaderType.SWEEP_SHADER);
        Shader saturationShader = new RadialShader(new Point(centerX, centerY), radius, new float[]{},
            new Color[]{Color.WHITE, new Color(0x00FFFFFF)}, Shader.TileMode.CLAMP_TILEMODE);
        saturationPaint.setShader(saturationShader, Paint.ShaderType.RADIAL_SHADER);
    }

    @Override
    public void invalidate() {
        super.invalidate();
        this.addDrawTask(this::onDraw);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        onSizeChanged(getWidth(), getHeight());
        canvas.drawCircle(centerX, centerY, radius, huePaint);
        canvas.drawCircle(centerX, centerY, radius, saturationPaint);
    }
}
